local zeshan = fk.CreateSkill{
  name = "lingling__zeshan",
}

Fk:loadTranslationTable{
  ["lingling__zeshan"] = "择善",
  [":lingling__zeshan"] = "每回合限一次，当其他角色获得你的牌时，你可以防止之，然后交给其等量牌。",

  ["#lingling__zeshan-invoke"] = "择善：%dest 即将获得你的%arg张牌，你可以改为交给其等量张牌",
}

zeshan:addEffect(fk.BeforeCardsMove, {
  anim_type = "defensive",
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(zeshan.name) and player:usedSkillTimes(zeshan.name, Player.HistoryTurn) == 0 then
      local dat = {}
      for _, move in ipairs(data) do
        if move.from == player and move.to and not move.to.dead and
          move.moveReason == fk.ReasonPrey and move.proposer ~= player then
          for _, info in ipairs(move.moveInfo) do
            if info.fromArea == Card.PlayerHand or info.fromArea == Card.PlayerEquip then
              dat[move.to] = dat[move.to] or {}
              table.insertIfNeed(dat[move.to], info.cardId)
            end
          end
        end
      end
      if next(dat) then
        event:setCostData(self, { extra_data = dat })
        return true
      end
    end
  end,
  on_trigger = function (self, event, target, player, data)
    local room = player.room
    local dat = event:getCostData(self).extra_data
    local targets = {}
    for p, _ in pairs(dat) do
      table.insertIfNeed(targets, p)
    end
    room:sortByAction(targets)
    for _, p in ipairs(targets) do
      if not player:hasSkill(zeshan.name) or player:usedSkillTimes(zeshan.name, Player.HistoryTurn) > 0 then return end
      if not p.dead then
        event:setCostData(self, { tos = {p}, cards = dat[p] })
        self:doCost(event, target, player, data)
      end
    end
  end,
  on_cost = function (self, event, target, player, data)
    local room = player.room
    local to = event:getCostData(self).tos[1]
    local n = #event:getCostData(self).cards
    local cards = room:askToCards(player, {
      min_num = n,
      max_num = n,
      include_equip = true,
      skill_name = zeshan.name,
      prompt = "#lingling__zeshan-invoke::"..to.id..":"..n,
      cancelable = true,
    })
    if #cards == n then
      event:setCostData(self, { tos = {to}, ids = event:getCostData(self).cards, cards = cards })
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local to = event:getCostData(self).tos[1]
    local ids = event:getCostData(self).ids
    local cards = event:getCostData(self).cards
    room:cancelMove(data, ids)
    room:moveCardTo(cards, Card.PlayerHand, to, fk.ReasonGive, zeshan.name, nil, false, player)
  end,
})

return zeshan
